package com.ydgk.controller;

import com.ydgk.bean.Detail;
import com.ydgk.bean.Furniture;
import com.ydgk.bean.FurnitureKinds;
import com.ydgk.bean.View;
import com.ydgk.service.*;
import com.ydgk.tool.Tool;
import com.ydgk.vo.AjaxResult;
import com.ydgk.vo.FurnitureDetail;
import com.ydgk.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/furniture")
@Controller
public class FurnitureController {

    @Autowired
    private FurnitureService furnitureService;

    @Autowired
    private ViewService viewService;

    @Autowired
    private DetailService detailService;

    @Autowired
    private FurnitureKindsService furnitureKindsService;

    @Autowired
    private Pre_orderService pre_orderService;

    private static final String UPLOAD_DIRECTORY = "upload/furniture";
    private static final String UPLOAD_DIRECTORY_VIEW = "upload/view";
    private static final String UPLOAD_DIRECTORY_DETAIL = "upload/detail";
    private static final String UPLOAD_DIRECTORY_FK = "upload/furnitureKinds";
    private static final Integer pageSize = 8;
    public static MultipartFile fileForFface = null;
    public static Map<String,MultipartFile> fileForView = new HashMap<String, MultipartFile>();
    public static Map<String,MultipartFile> fileForDetail = new HashMap<String, MultipartFile>();
    public static Map<Integer,MultipartFile> fileForFkface = new HashMap<Integer, MultipartFile>();
    public static Map<Integer,FurnitureKinds> furnitureKindsMap = new HashMap<Integer, FurnitureKinds>();

    @ModelAttribute
    public void getFurnitureDetail(@RequestParam(value = "fid" , required = false , defaultValue = "0") Integer fid, Map map){
        if(fid != 0){
            Furniture furniture = furnitureService.findById(fid);
            List<View> viewList = viewService.findByFid(fid);
            List<Detail> detailList = detailService.findByFid(fid);
            List<FurnitureKinds> furnitureKindsList = furnitureKindsService.findByFid(fid);
            map.put("furniture",furniture);
            map.put("viewList",viewList);
            map.put("detailList",detailList);
            map.put("furnitureKindsList",furnitureKindsList);
        }
    }

    @ResponseBody
    @RequestMapping("/ffaceUpload")
    public AjaxResult ffaceUpload(@RequestParam("file") MultipartFile file) throws IOException {
        this.fileForFface = file;
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/fkfaceUpload")
    public AjaxResult fkfaceUpload(@RequestParam("file") MultipartFile file,Integer count) throws IOException {
        this.fileForFkface.put(count,file);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/viewUpload")
    public AjaxResult viewUpload(@RequestParam("file") MultipartFile file) throws IOException {
        this.fileForView.put(file.getOriginalFilename(),file);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/detailUpload")
    public AjaxResult detailUpload(@RequestParam("file") MultipartFile file) throws IOException {
        this.fileForDetail.put(file.getOriginalFilename(),file);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/fileDelete")
    public AjaxResult fileDelete(String name,String flag) throws IOException {
        if(flag.equals("view")){
            this.fileForView.remove(name);
        }else if(flag.equals("detail")){
            this.fileForDetail.remove(name);
        }
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/insertFurnitureKinds")
    public AjaxResult insertFurnitureKinds(FurnitureKinds furnitureKinds, Integer count) {
        this.furnitureKindsMap.put(count,furnitureKinds);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/insertFurniture", method = RequestMethod.POST)
    public AjaxResult insertFurniture(Furniture furniture, Integer ktid, HttpServletRequest request) throws IOException {
        String newfilename = Tool.upload(request,fileForFface,UPLOAD_DIRECTORY );
        furniture.setFface(UPLOAD_DIRECTORY + "/" + newfilename);
        furniture.setKt_ktid(ktid);
        furniture.setMarkettime(new Timestamp(System.currentTimeMillis()));
        furniture.setSales(0);
        furniture.setCondition(1);
        AjaxResult ajaxResult = new AjaxResult();
        try{
            furnitureService.insert(furniture);
            int fid = furniture.getFid();
            if(fid > 0){
                Collection<MultipartFile> views = fileForView.values();
                View view = new View();
                String viewname = "";
                for (MultipartFile file : views) {
                    viewname = Tool.upload(request,file,UPLOAD_DIRECTORY_VIEW);
                    view.setVphoto(UPLOAD_DIRECTORY_VIEW + "/" + viewname);
                    view.setF_fid(fid);
                    viewService.insert(view);
                }
                Collection<MultipartFile> details = fileForDetail.values();
                Detail detail = new Detail();
                String detailname = "";
                for (MultipartFile file : details) {
                    detailname = Tool.upload(request,file,UPLOAD_DIRECTORY_DETAIL);
                    detail.setDphoto(UPLOAD_DIRECTORY_DETAIL + "/" + detailname);
                    detail.setF_fid(fid);
                    detailService.insert(detail);
                }

                FurnitureKinds furnitureKinds = null;
                String fkfacename = "";
                for (int i = 1; i <= furnitureKindsMap.size(); i++) {
                    fkfacename = Tool.upload(request,fileForFkface.get(i),UPLOAD_DIRECTORY_FK);
                    furnitureKinds = furnitureKindsMap.get(i);
                    furnitureKinds.setFkface(UPLOAD_DIRECTORY_FK + "/" + fkfacename);
                    furnitureKinds.setSales(0);
                    furnitureKinds.setF_fid(fid);
                    furnitureKindsService.insert(furnitureKinds);
                }
            }
            ajaxResult.setSuccess(true);
        }catch (Exception e){
            ajaxResult.setSuccess(false);
        }
        clear();
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/findAll" , method = RequestMethod.POST)
    public AjaxResult findAll(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                    @RequestParam(value = "sort", required = false, defaultValue = "0") Integer sort,
                                    @RequestParam(value = "type", required = false, defaultValue = "") String type,
                                    @RequestParam(value = "likeName" , required = false, defaultValue = "") String likeName, Integer ktid) {
        AjaxResult ajaxResult = new AjaxResult();
        try{

            // 将请求参数封装成一个map
            Map<String, Object> factorMap = new HashMap<String, Object>();
            factorMap.put("ktid",ktid);
            factorMap.put("type", type);
            factorMap.put("likeName",likeName);

            int count = furnitureService.findAllCount(factorMap);
            Integer pageTotal = 0;
            if(count <= pageSize){
                pageTotal = 1;
            }else{
                if (count % pageSize == 0) {
                    pageTotal = count / pageSize;
                } else {
                    pageTotal = count / pageSize + 1;
                }
            }
            if(pageNo > pageTotal){
                pageNo = pageTotal;
            }
            if(pageNo < 1){
                pageNo = 1;
            }

            Integer pageStart = (pageNo - 1) * pageSize;
            factorMap.put("start", pageStart);
            factorMap.put("size", pageSize);
            factorMap.put("sort", sort);

            List<Furniture> furnitureList =  furnitureService.findAll(factorMap);

            String pageContent = Tool.getPageContent(pageNo,pageTotal,type);
            Page<Furniture> page = new Page(furnitureList, pageNo, pageTotal,count,pageContent);
            ajaxResult.setData(page);
            ajaxResult.setSuccess(true);
        }catch (Exception e){
            ajaxResult.setSuccess(false);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteFurniture/{fid}", method = RequestMethod.DELETE)
    public AjaxResult deleteFurniture(@PathVariable("fid") Integer fid, HttpServletRequest request, Furniture furniture, List<View> viewList, List<Detail> detailList, List<FurnitureKinds> furnitureKindsList) {
        ServletContext application = request.getServletContext();
        AjaxResult ajaxResult = new AjaxResult();
        try {
            int i = furnitureService.deleteById(fid);
            if (i > 0) {
                String fface = furniture.getFface();
                new File(application.getRealPath("/"+fface)).delete();
                String vphoto = "";
                for (View view : viewList) {
                    vphoto = view.getVphoto();
                    new File(application.getRealPath("/"+vphoto)).delete();
                }
                String dphoto = "";
                for (Detail detail : detailList) {
                    dphoto = detail.getDphoto();
                    new File(application.getRealPath("/"+dphoto)).delete();
                }
                String fkface = "";
                for (FurnitureKinds furnitureKinds : furnitureKindsList) {
                    fkface = furnitureKinds.getFkface();
                    new File(application.getRealPath("/"+fkface)).delete();
                }
                ajaxResult.setSuccess(true);
            } else {
                ajaxResult.setSuccess(false);
            }
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            e.printStackTrace();
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/setCondition")
    public AjaxResult setCondition(@RequestParam(value = "batchFid[]")  Integer[]  batchFid, Integer val) {
        AjaxResult ajaxResult = new AjaxResult();
        for (int i = 0; i < batchFid.length; i++) {
            if(val == 1){
                if(viewService.findByFid(batchFid[i]).size() == 0 || detailService.findByFid(batchFid[i]).size() == 0 || furnitureKindsService.findByFid(batchFid[i]).size() == 0){
                    ajaxResult.setSuccess(false);
                    return ajaxResult;
                }
            }
            furnitureService.setCondition(batchFid[i],val);
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteFurnitureBatch")
    public AjaxResult deleteFurnitureBatch(@RequestParam(value = "batchFid[]")  Integer[]  batchFid, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        for (int i = 0; i < batchFid.length; i++) {
            int count = pre_orderService.findCountByFid(batchFid[i]);
            if(count > 0 ){
                ajaxResult.setSuccess(false);
                return ajaxResult;
            }
        }
        for (int i = 0; i < batchFid.length; i++) {
            Furniture furniture = furnitureService.findById(batchFid[i]);
            List<View> viewList = viewService.findByFid(batchFid[i]);
            List<Detail> detailList = detailService.findByFid(batchFid[i]);
            List<FurnitureKinds> furnitureKindsList = furnitureKindsService.findByFid(batchFid[i]);
            ajaxResult = deleteFurniture(batchFid[i],request,furniture,viewList,detailList,furnitureKindsList);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/findNewFurniture")
    public AjaxResult findNewFurniture(@RequestParam("count") Integer count, Integer ktid) {
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> factorMap = new HashMap<String, Object>();
        factorMap.put("ktid",ktid);
        factorMap.put("type", "onSale");
        factorMap.put("sort",5);
        factorMap.put("start", 0);
        factorMap.put("size", count);
        try{
            List<Furniture> furnitureList =  furnitureService.findAll(factorMap);
            Page<Furniture> page = new Page(furnitureList, null, null,count,null);
            ajaxResult.setData(page);
            ajaxResult.setSuccess(true);
        }catch (Exception e){
            ajaxResult.setSuccess(false);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/updateInfo/{fid}",method = RequestMethod.PUT)
    public AjaxResult updateFurnitureInfo(Furniture furniture) {
        AjaxResult ajaxResult = new AjaxResult();
        int i = furnitureService.updateById(furniture);
        if(i > 0){
            ajaxResult.setSuccess(true);
        }else{
            ajaxResult.setSuccess(false);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/updateFace")
    public AjaxResult updateFurnitureFace(Furniture furniture, HttpServletRequest request) throws IOException {
        ServletContext application = request.getServletContext();
        String newfilename = Tool.upload(request,fileForFface,UPLOAD_DIRECTORY );
        String fface = furniture.getFface();
        furniture.setFface(UPLOAD_DIRECTORY + "/" + newfilename);
        int i = furnitureService.updateById(furniture);
        AjaxResult ajaxResult = new AjaxResult();
        if( i > 0){
            new File(application.getRealPath("/"+fface)).delete();
            clear();
            ajaxResult.setSuccess(true);
        }else{
            ajaxResult.setSuccess(false);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/getFurnitureDetail")
    public AjaxResult getFurnitureDetail(Furniture furniture, List<View> viewList, List<Detail> detailList, List<FurnitureKinds> furnitureKindsList){
        AjaxResult ajaxResult = new AjaxResult();
        FurnitureDetail furnitureDetail = new FurnitureDetail(furniture,viewList,detailList,furnitureKindsList);
        ajaxResult.setData(furnitureDetail);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    public static void clear(){
        fileForFface = null;
        fileForView.clear();
        fileForDetail.clear();
        fileForFkface.clear();
        furnitureKindsMap.clear();
    }
}
